package com.wj.chatroom.mapper;

import com.wj.chatroom.model.Friend;
import com.wj.chatroom.model.MessageSession;
import com.wj.chatroom.model.MessageSessionUserItem;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Select;

import java.util.List;

@Mapper
public interface MessageSessionMapper {
    //根据userId获取到用户在哪些会话中存在，返回结果是一组sessionId
    //当存在多个会话时，最新的会话应该出现在会话列表的最上面
    @Select("select sessionId from message_session where sessionId in (select sessionId from" +
            " message_session_user where userId = #{userId}) order by lastTime desc")
    List<Integer> getSessionIdsByUserId(int userId);

    //根据sessionId再来查询这个会话中包含了哪些用户(不算自己)
    @Select("select userId as friendId ,username as friendName from user " +
            "where userId in(select userId from message_session_user " +
            "where sessionId =#{sessionId} and userId!=#{selfUserId})")
    List<Friend> getFriendsBySessionId(int sessionId, int selfUserId);

    @Options(useGeneratedKeys = true, keyProperty = "sessionId")
    @Insert("insert into message_session values(null, now())")
        //新增一个会话记录，返回会话的id
    Integer addMessageSession(MessageSession messageSession);

    //给message_session_user 表里也新增对应的记录
    @Insert("insert into message_session_user values(#{sessionId},#{userId})")
    void addMessageSessionUser(MessageSessionUserItem messageSessionUserItem);
}